<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理员仪表板 - OpenOKR</title>
    <link rel="stylesheet" href="/static/css/style.css">
</head>
<body>
    <nav class="navbar">
        <a href="/" class="navbar-brand" style="display: flex; align-items: center; gap: 0.5rem;">
            <img src="/static/images/openokr.png" alt="OpenOKR" style="height: 32px; width: auto;">
            <span>OpenOKR</span>
        </a>
        <ul class="navbar-menu">
            <li><a href="/auth/dashboard">仪表板</a></li>
            <li><a href="#" onclick="logout()">登出</a></li>
        </ul>
    </nav>

    <div class="container-fluid">
        <h1 style="margin-bottom: 2rem;">管理员仪表板</h1>

        <!-- 系统统计 -->
        <div class="grid grid-4">
            <div class="card">
                <div class="card-header">用户总数</div>
                <div class="card-body" style="text-align: center;">
                    <div style="font-size: 2.5rem; font-weight: 700; color: var(--primary-color);" id="total-users">-</div>
                </div>
            </div>
            <div class="card">
                <div class="card-header">目标总数</div>
                <div class="card-body" style="text-align: center;">
                    <div style="font-size: 2.5rem; font-weight: 700; color: var(--success-color);" id="total-objectives">-</div>
                </div>
            </div>
            <div class="card">
                <div class="card-header">项目总数</div>
                <div class="card-body" style="text-align: center;">
                    <div style="font-size: 2.5rem; font-weight: 700; color: var(--warning-color);" id="total-projects">-</div>
                </div>
            </div>
            <div class="card">
                <div class="card-header">活跃目标</div>
                <div class="card-body" style="text-align: center;">
                    <div style="font-size: 2.5rem; font-weight: 700; color: var(--danger-color);" id="active-objectives">-</div>
                </div>
            </div>
        </div>

        <!-- 用户管理 -->
        <div class="card">
            <div class="card-header">
                👥 用户管理
                <button onclick="openModal('create-user-modal')" class="btn btn-primary" style="float: right;">创建用户</button>
            </div>
            <div class="card-body">
                <table class="table" id="users-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>用户名</th>
                            <th>姓名</th>
                            <th>邮箱</th>
                            <th>角色</th>
                            <th>部门</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="users-tbody">
                        <tr>
                            <td colspan="8" style="text-align: center;">加载中...</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- 数据库管理 -->
        <div class="card">
            <div class="card-header">🗄️ 数据库管理</div>
            <div class="card-body">
                <button onclick="initDatabase()" class="btn btn-success">初始化示例数据</button>
                <p style="margin-top: 1rem; color: var(--text-secondary);">
                    注意：这将创建示例用户和数据（仅当数据库为空时）
                </p>
            </div>
        </div>
    </div>

    <!-- 创建用户模态框 -->
    <div id="create-user-modal" class="modal">
        <div class="modal-content">
            <div class="modal-header">创建新用户</div>
            <form id="create-user-form">
                <div class="form-group">
                    <label class="form-label">用户名</label>
                    <input type="text" name="username" class="form-input" required>
                </div>
                <div class="form-group">
                    <label class="form-label">密码</label>
                    <input type="password" name="password" class="form-input" required>
                </div>
                <div class="form-group">
                    <label class="form-label">姓名</label>
                    <input type="text" name="full_name" class="form-input" required>
                </div>
                <div class="form-group">
                    <label class="form-label">邮箱</label>
                    <input type="email" name="email" class="form-input" required>
                </div>
                <div class="grid grid-2">
                    <div class="form-group">
                        <label class="form-label">角色</label>
                        <select name="role" class="form-select" required>
                            <option value="employee">员工</option>
                            <option value="manager">主管</option>
                            <option value="admin">管理员</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">部门</label>
                        <input type="text" name="department" class="form-input">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" onclick="closeModal('create-user-modal')" class="btn btn-secondary">取消</button>
                    <button type="submit" class="btn btn-primary">创建</button>
                </div>
            </form>
        </div>
    </div>

    <script src="/static/js/common.js"></script>
    <script>
        // 加载系统统计
        async function loadSystemStats() {
            try {
                const stats = await apiRequest('/api/admin/stats');

                document.getElementById('total-users').textContent = stats.users.total;
                document.getElementById('total-objectives').textContent = stats.objectives.total;
                document.getElementById('total-projects').textContent = stats.projects.total;
                document.getElementById('active-objectives').textContent = stats.objectives.active;
            } catch (error) {
                showNotification('加载统计数据失败', 'error');
            }
        }

        // 加载用户列表
        async function loadUsers() {
            try {
                const users = await apiRequest('/api/admin/users');
                const tbody = document.getElementById('users-tbody');

                if (users.length === 0) {
                    tbody.innerHTML = '<tr><td colspan="8" style="text-align: center;">暂无用户</td></tr>';
                    return;
                }

                const roleMap = {
                    'admin': '管理员',
                    'manager': '主管',
                    'employee': '员工'
                };

                tbody.innerHTML = users.map(user => `
                    <tr>
                        <td>${user.id}</td>
                        <td>${user.username}</td>
                        <td>${user.full_name}</td>
                        <td>${user.email}</td>
                        <td><span class="badge badge-${user.role === 'admin' ? 'danger' : user.role === 'manager' ? 'warning' : 'primary'}">
                            ${roleMap[user.role] || user.role}</span></td>
                        <td>${user.department || '-'}</td>
                        <td>${formatDate(user.created_at)}</td>
                        <td>
                            <button class="btn btn-danger" style="font-size: 0.75rem; padding: 0.25rem 0.5rem;"
                                    onclick="deleteUser(${user.id}, '${user.username}')">删除</button>
                        </td>
                    </tr>
                `).join('');
            } catch (error) {
                showNotification('加载用户列表失败', 'error');
            }
        }

        // 创建用户
        document.getElementById('create-user-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = new FormData(e.target);
            const data = Object.fromEntries(formData);

            try {
                await apiRequest('/auth/register', {
                    method: 'POST',
                    body: JSON.stringify(data)
                });
                showNotification('用户创建成功', 'success');
                closeModal('create-user-modal');
                e.target.reset();
                loadUsers();
                loadSystemStats();
            } catch (error) {
                showNotification('创建失败: ' + error.message, 'error');
            }
        });

        // 删除用户
        async function deleteUser(userId, username) {
            if (!confirm(`确定要删除用户 "${username}" 吗？此操作不可恢复。`)) {
                return;
            }

            try {
                await apiRequest(`/api/admin/users/${userId}`, {
                    method: 'DELETE'
                });
                showNotification('用户删除成功', 'success');
                loadUsers();
                loadSystemStats();
            } catch (error) {
                showNotification('删除失败: ' + error.message, 'error');
            }
        }

        // 初始化数据库
        async function initDatabase() {
            if (!confirm('确定要初始化示例数据吗？此操作仅在数据库为空时执行。')) {
                return;
            }

            try {
                const result = await apiRequest('/api/admin/init-db', {
                    method: 'POST'
                });
                showNotification(result.message, 'success');
                loadUsers();
                loadSystemStats();
            } catch (error) {
                showNotification('初始化失败: ' + error.message, 'error');
            }
        }

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', () => {
            loadSystemStats();
            loadUsers();
        });
    </script>
</body>
</html>